﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using Utility;

namespace CookingPlan
{
    class Program
    {
        static void Main(string[] args)
        {
            if (args.Length == 6 && args.Contains("-f") && args[5] != "-f" && args.Contains("-p") && args[5] != "-p" &&
                args.Contains("-r") && args[5] != "-r")
            {
                string pathSource = args[GetIndex(args, "-f") + 1];
                string pathPlan = args[GetIndex(args, "-p") + 1];
                string pathReport = args[GetIndex(args, "-r") + 1];
                if (!File.Exists(pathSource))
                {
                    Console.WriteLine("Error in argument -f");
                    return;
                }
                if (!Directory.Exists(pathPlan))
                {
                    Console.WriteLine("Error in argument -p");
                    return;
                }
                if (!Directory.Exists(pathReport))
                {
                    Console.WriteLine("Error in argument -r");
                    return;
                }
                IEnumerable<TimeRecipeTuple> tuples = GetTuples(pathSource);
                //菜谱分析
                var recipeAnalysis = new RecipeAnalysis(tuples);
                //烹饪计划
                PlanFile.GetPlanFile(recipeAnalysis.RecipeFiles, recipeAnalysis.GetAllIngredients(),
                                     recipeAnalysis.TimeRecipeTuple, pathPlan);
                //食材报告
                IngredientsReport.GetReportFile(recipeAnalysis.GetAllIngredients(), pathReport);
            }
            else
            {
                Console.WriteLine("Error in arguments");
            }
        }

        //在字符串数组中查找某一值的位置
        private static int GetIndex(string[] args, string s)
        {
            int res = 0;
            for(;res<args.Length;res++)
            {
                if(args[res] == s)
                {
                    break;
                }
            }
            return res;
        }

        //读取-f参数所表示的文件
        private static IEnumerable<TimeRecipeTuple> GetTuples(string path)
        {
            StreamReader sr = File.OpenText(path);
            string[] tuples = sr.ReadToEnd().Trim().Replace("\r\n", "\n").Split('\n');
            sr.Close();
            return
                tuples.Select(t => t.Split('=')).Select(
                    timeRecipe => new TimeRecipeTuple {Time = timeRecipe[0], RecipeFile = timeRecipe[1]}).ToList();
        }
    }
}
